import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useArchivesStore = defineStore('archives', () => {
  // 状态
  const archives = ref([])
  const loading = ref(false)
  const searchQuery = ref('')
  const filters = ref({
    status: 'all', // all, alive, dead
    gender: 'all', // all, male, female
    ageRange: [0, 200]
  })

  // 生成假数据
  const generateMockData = () => {
    // 更丰富的姓氏数据
    const surnames = [
      '张',
      '李',
      '王',
      '刘',
      '陈',
      '杨',
      '赵',
      '黄',
      '周',
      '吴',
      '徐',
      '孙',
      '胡',
      '朱',
      '高',
      '林',
      '何',
      '郭',
      '马',
      '罗',
      '梁',
      '宋',
      '郑',
      '谢',
      '韩',
      '唐',
      '冯',
      '于',
      '董',
      '萧',
      '程',
      '柴',
      '袁',
      '邓',
      '许',
      '傅',
      '沈',
      '曾',
      '彭',
      '吕',
      '苏',
      '卢',
      '蒋',
      '蔡',
      '贾',
      '丁',
      '魏',
      '薛',
      '叶',
      '阎'
    ]

    // 更丰富的男性名字
    const maleNames = [
      '文华',
      '志强',
      '建国',
      '国强',
      '志明',
      '建华',
      '德华',
      '志勇',
      '永强',
      '建军',
      '子轩',
      '浩然',
      '宇航',
      '思远',
      '博文',
      '天佑',
      '锦程',
      '煜祺',
      '明轩',
      '俊杰',
      '承志',
      '敬业',
      '立功',
      '安邦',
      '治国',
      '福贵',
      '荣华',
      '康宁',
      '吉祥',
      '如意',
      '景行',
      '思齐',
      '正心',
      '修身',
      '齐家',
      '治平',
      '明德',
      '厚德',
      '载物',
      '自强'
    ]

    // 更丰富的女性名字
    const femaleNames = [
      '美丽',
      '秀英',
      '桂花',
      '月华',
      '春梅',
      '秋菊',
      '冬雪',
      '夏荷',
      '芳草',
      '如花',
      '若汐',
      '语嫣',
      '诗涵',
      '雨萱',
      '梦琪',
      '心怡',
      '紫涵',
      '佳怡',
      '思涵',
      '静怡',
      '淑雯',
      '婉清',
      '雅静',
      '端庄',
      '贤淑',
      '温柔',
      '娴静',
      '优雅',
      '清丽',
      '秀美',
      '慧心',
      '兰心',
      '蕙质',
      '芳华',
      '倾城',
      '绝代',
      '风华',
      '绝世',
      '倾国',
      '姿色'
    ]

    // 更真实的地址数据
    const provinces = [
      { name: '北京市', cities: ['朝阳区', '海淀区', '西城区', '东城区', '丰台区', '石景山区', '通州区', '昌平区'] },
      { name: '上海市', cities: ['浦东新区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '黄浦区'] },
      { name: '广东省', cities: ['广州市天河区', '深圳市南山区', '珠海市香洲区', '东莞市莞城区', '佛山市禅城区', '中山市石岐区'] },
      { name: '江苏省', cities: ['南京市鼓楼区', '苏州市姑苏区', '无锡市梁溪区', '常州市天宁区', '徐州市鼓楼区', '南通市崇川区'] },
      { name: '浙江省', cities: ['杭州市西湖区', '宁波市鄞州区', '温州市鹿城区', '嘉兴市南湖区', '绍兴市越城区', '金华市婺城区'] },
      { name: '山东省', cities: ['济南市历下区', '青岛市市南区', '烟台市芝罘区', '潍坊市潍城区', '临沂市兰山区', '济宁市任城区'] },
      { name: '河南省', cities: ['郑州市金水区', '洛阳市西工区', '开封市鼓楼区', '新乡市红旗区', '焦作市解放区', '安阳市文峰区'] },
      { name: '四川省', cities: ['成都市锦江区', '绵阳市涪城区', '德阳市旌阳区', '南充市顺庆区', '宜宾市翠屏区', '泸州市江阳区'] },
      { name: '湖北省', cities: ['武汉市武昌区', '宜昌市西陵区', '襄阳市樊城区', '荆州市沙市区', '黄石市黄石港区', '十堰市茅箭区'] },
      { name: '湖南省', cities: ['长沙市岳麓区', '株洲市天元区', '湘潭市雨湖区', '衡阳市珠晖区', '邵阳市双清区', '岳阳市岳阳楼区'] }
    ]

    // 更丰富的职业数据
    const professions = [
      // 传统职业
      '商人',
      '农民',
      '工匠',
      '学者',
      '医师',
      '教师',
      '官员',
      '军人',
      '僧侣',
      '道士',
      '书生',
      '画师',
      '音乐师',
      '织工',
      '铁匠',
      '木匠',
      '石匠',
      '厨师',
      '酿酒师',
      '茶商',
      '药铺掌柜',
      '当铺老板',
      '丝绸商',
      '粮商',
      '布商',
      '珠宝商',
      '古董商',
      '书商',
      '药材商',
      '茶叶商',
      // 现代职业
      '工程师',
      '医生',
      '律师',
      '会计师',
      '设计师',
      '程序员',
      '销售员',
      '经理',
      '主管',
      '顾问',
      '研究员',
      '分析师',
      '策划师',
      '编辑',
      '记者',
      '翻译',
      '导游',
      '司机',
      '保安',
      '清洁工'
    ]

    // 更丰富的学历数据
    const educations = ['私塾启蒙', '县学', '府学', '太学', '国子监', '书院', '科举进士', '科举举人', '科举秀才', '小学', '中学', '高中', '大专', '本科', '硕士', '博士', '博士后']

    // 更丰富的生命事件
    const eventTypes = [
      { type: 'birth', titles: ['降生人世', '呱呱坠地', '出生登记', '初来乍到'] },
      { type: 'education', titles: ['启蒙求学', '入学读书', '拜师学艺', '科举考试', '学成毕业', '深造进修'] },
      { type: 'career', titles: ['初入职场', '开始从业', '创业立业', '职位升迁', '转行发展', '退休告老'] },
      { type: 'marriage', titles: ['订婚结缘', '成家立业', '喜结连理', '洞房花烛', '金婚庆典'] },
      { type: 'family', titles: ['子女降生', '添丁进口', '家庭团聚', '搬迁新居', '家业兴旺'] },
      { type: 'achievement', titles: ['功名成就', '德行彰显', '技艺精进', '学术成果', '商业成功', '慈善善举'] },
      { type: 'travel', titles: ['远行游历', '迁徙定居', '朝圣之旅', '商务出行', '探亲访友'] },
      { type: 'health', titles: ['大病初愈', '身体康复', '养生有成', '长寿之道'] },
      { type: 'social', titles: ['结交益友', '社团活动', '公益参与', '邻里和睦'] }
    ]

    return Array.from({ length: 50 }, (_, index) => {
      const gender = Math.random() > 0.5 ? 'male' : 'female'
      const surname = surnames[Math.floor(Math.random() * surnames.length)]
      const firstName = gender === 'male' ? maleNames[Math.floor(Math.random() * maleNames.length)] : femaleNames[Math.floor(Math.random() * femaleNames.length)]

      const birthYear = 1920 + Math.floor(Math.random() * 90)
      const currentYear = new Date().getFullYear()
      const age = currentYear - birthYear
      const lifespan = 60 + Math.floor(Math.random() * 40)
      const isAlive = age < lifespan && Math.random() > 0.3

      const id = 1000 + index + 1

      // 随机选择省份和城市
      const province = provinces[Math.floor(Math.random() * provinces.length)]
      const city = province.cities[Math.floor(Math.random() * province.cities.length)]
      const birthPlace = `${province.name}${city}`

      // 随机选择另一个地址作为现住址
      const currentProvince = provinces[Math.floor(Math.random() * provinces.length)]
      const currentCity = currentProvince.cities[Math.floor(Math.random() * currentProvince.cities.length)]
      const currentAddress = `${currentProvince.name}${currentCity}${Math.floor(Math.random() * 999) + 1}号`

      // 生成更丰富的生命事件
      const generateLifeEvents = () => {
        const events = []
        let eventId = 1

        // 出生事件
        events.push({
          id: eventId++,
          date: `${birthYear}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
          type: 'birth',
          title: eventTypes[0].titles[Math.floor(Math.random() * eventTypes[0].titles.length)],
          description: `于${birthPlace}降生，家族添丁进口，众人欢喜`,
          importance: 'high'
        })

        // 随机生成其他生命事件
        const eventCount = 8 + Math.floor(Math.random() * 12) // 8-20个事件
        for (let i = 1; i < eventCount && birthYear + i * 2 < currentYear; i++) {
          const eventAge = i * 2 + Math.floor(Math.random() * 5)
          const eventYear = birthYear + eventAge

          if (eventYear > currentYear || (!isAlive && eventYear > birthYear + lifespan)) break

          const eventCategory = eventTypes[Math.floor(Math.random() * eventTypes.length)]
          const eventTitle = eventCategory.titles[Math.floor(Math.random() * eventCategory.titles.length)]

          events.push({
            id: eventId++,
            date: `${eventYear}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
            type: eventCategory.type,
            title: eventTitle,
            description: generateEventDescription(eventCategory.type, eventTitle, eventAge),
            importance: ['low', 'medium', 'high'][Math.floor(Math.random() * 3)]
          })
        }

        return events.sort((a, b) => new Date(a.date) - new Date(b.date))
      }

      // 生成事件描述
      const generateEventDescription = (type, title, age) => {
        const descriptions = {
          education: [`${age}岁时开始${title}，勤奋好学，成绩优异`, `在${age}岁时${title}，师从名师，学有所成`],
          career: [`${age}岁${title}，凭借才能和努力获得认可`, `年${age}岁时${title}，展现出卓越的工作能力`],
          marriage: [`${age}岁时${title}，与心爱之人结为伴侣，举办了盛大的婚礼`, `年${age}岁${title}，家族联姻，门第相当`],
          family: [`${age}岁时${title}，家庭美满，子女孝顺`, `年${age}岁${title}，家族兴旺，传承有序`],
          achievement: [`${age}岁时${title}，在社会上获得了广泛认可`, `年${age}岁${title}，成为当地的知名人士`],
          travel: [`${age}岁时${title}，见识了广阔的世界`, `年${age}岁${title}，增长了见识和阅历`],
          health: [`${age}岁时${title}，身体状况良好`, `年${age}岁${title}，注重养生之道`],
          social: [`${age}岁时${title}，在社交圈中颇受欢迎`, `年${age}岁${title}，结交了许多益友`]
        }

        const typeDescriptions = descriptions[type] || [`${age}岁时${title}，这是人生的重要时刻`]
        return typeDescriptions[Math.floor(Math.random() * typeDescriptions.length)]
      }

      // 生成业力值
      const karma = Math.floor(Math.random() * 201) - 100 // -100 到 100

      return {
        // 基础信息
        id,
        name: surname + firstName,
        gender,
        age: isAlive ? age : Math.min(age, lifespan),
        status: isAlive ? 'alive' : 'dead',
        karma,
        lifespan,
        avatar: `/avatars/${gender === 'male' ? 'male' : 'female'}-${(index % 10) + 1}.png`,

        // 个人基础信息
        basicInfo: {
          fullName: surname + firstName,
          nickname: Math.random() > 0.7 ? `${firstName.charAt(firstName.length - 1)}${['子', '儿', '哥', '姐', '妹'][Math.floor(Math.random() * 5)]}` : '',
          idCard: `${Math.floor(Math.random() * 900000) + 100000}${birthYear}${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}${Math.floor(Math.random() * 9000) + 1000}`,
          birthPlace,
          currentAddress,
          nationality: ['汉族', '满族', '蒙古族', '回族', '藏族', '维吾尔族', '苗族', '彝族', '壮族', '布依族'][Math.floor(Math.random() * 10)],
          bloodType: ['A', 'B', 'AB', 'O'][Math.floor(Math.random() * 4)],
          profession: professions[Math.floor(Math.random() * professions.length)],
          education: educations[Math.floor(Math.random() * educations.length)],
          maritalStatus: ['未婚', '已婚', '丧偶', '离异'][Math.floor(Math.random() * 4)],
          height: 150 + Math.floor(Math.random() * 30), // 150-180cm
          weight: 45 + Math.floor(Math.random() * 40), // 45-85kg
          personalityTraits: ['善良', '勤劳', '智慧', '勇敢', '诚实', '幽默', '温和', '坚强', '乐观', '谦逊'].slice(0, Math.floor(Math.random() * 5) + 2)
        },

        // 生命历程
        lifeHistory: {
          birthDate: `${birthYear}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
          deathDate: isAlive ? null : `${birthYear + lifespan}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
          majorEvents: generateLifeEvents(),
          growthTrack: [
            { age: 0, event: '降生人世', karma: 0, description: '初来人间，纯真无邪' },
            { age: 6, event: '启蒙教育', karma: 5, description: '开始接受教育，懂得礼仪' },
            { age: 16, event: '成年礼', karma: 10, description: '步入成年，承担责任' },
            { age: 25, event: '立业成家', karma: 15, description: '事业有成，家庭美满' },
            { age: 40, event: '人生中年', karma: Math.floor(Math.random() * 50), description: '阅历丰富，德行深厚' },
            { age: 60, event: '花甲之年', karma: Math.floor(Math.random() * 80), description: '智慧圆满，德高望重' }
          ].filter((track) => track.age <= (isAlive ? age : lifespan)),
          achievements: ['品德高尚', '孝敬父母', '勤劳致富', '乐善好施', '扶贫济困', '教育子女', '敬业爱岗', '技艺精湛', '学识渊博', '德艺双馨', '造福一方', '功德无量'].slice(0, Math.floor(Math.random() * 6) + 2),
          lifePhilosophy: ['修身齐家治国平天下', '己所不欲勿施于人', '天行健君子以自强不息', '地势坤君子以厚德载物', '学而时习之不亦说乎', '三人行必有我师焉'][Math.floor(Math.random() * 6)]
        },

        // 社会关系网络
        socialNetwork: {
          family: {
            parents: [
              { name: `${surname}${gender === 'male' ? '父' : '母'}`, relation: '父亲', status: Math.random() > 0.6 ? 'alive' : 'dead', age: age + 25 + Math.floor(Math.random() * 10) },
              { name: `${['陈', '李', '王', '刘', '杨'][Math.floor(Math.random() * 5)]}氏`, relation: '母亲', status: Math.random() > 0.6 ? 'alive' : 'dead', age: age + 23 + Math.floor(Math.random() * 8) }
            ],
            spouse:
              Math.random() > 0.3
                ? {
                    name: `${['陈', '李', '王', '刘', '杨', '赵', '周', '吴', '郑', '孙'][Math.floor(Math.random() * 10)]}${gender === 'male' ? '氏' : firstName}`,
                    status: isAlive ? (Math.random() > 0.1 ? 'alive' : 'dead') : Math.random() > 0.5 ? 'alive' : 'dead',
                    marriageDate: `${birthYear + 20 + Math.floor(Math.random() * 10)}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
                    relationship: '恩爱有加'
                  }
                : null,
            children: Array.from({ length: Math.floor(Math.random() * 5) }, (_, i) => ({
              name: `${surname}${['长', '次', '三', '四', '五'][i]}${gender === 'male' ? (Math.random() > 0.5 ? '子' : '女') : Math.random() > 0.5 ? '儿' : '女'}`,
              relation: Math.random() > 0.5 ? '儿子' : '女儿',
              status: 'alive',
              age: Math.max(1, age - 20 - Math.floor(Math.random() * 15)),
              character: ['聪慧', '孝顺', '勤奋', '善良', '活泼'][Math.floor(Math.random() * 5)]
            })),
            siblings: Array.from({ length: Math.floor(Math.random() * 4) }, (_, i) => ({
              name: `${surname}${['兄', '弟', '姐', '妹'][i]}`,
              relation: ['兄长', '弟弟', '姐姐', '妹妹'][i],
              status: Math.random() > 0.2 ? 'alive' : 'dead',
              age: age + (i < 2 ? Math.floor(Math.random() * 5) + 1 : -(Math.floor(Math.random() * 5) + 1)),
              relationship: '手足情深'
            })),
            grandparents:
              Math.random() > 0.7
                ? [
                    { name: `${surname}老太爷`, relation: '祖父', status: 'dead', legacy: '家族兴旺' },
                    { name: `${surname}老太君`, relation: '祖母', status: 'dead', legacy: '德行传承' }
                  ]
                : []
          },
          friends: Array.from({ length: Math.floor(Math.random() * 8) + 2 }, (_, i) => ({
            name: `${surnames[Math.floor(Math.random() * surnames.length)]}${(gender === 'male' ? maleNames : femaleNames)[Math.floor(Math.random() * (gender === 'male' ? maleNames.length : femaleNames.length))]}`,
            type: ['挚友', '知己', '好友', '朋友', '同窗', '同事', '邻居'][Math.floor(Math.random() * 7)],
            intimacy: 50 + Math.floor(Math.random() * 50),
            acquaintanceDate: `${birthYear + 15 + Math.floor(Math.random() * 20)}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
            commonInterests: ['读书', '下棋', '品茶', '书法', '绘画', '音乐', '旅游', '商业'][Math.floor(Math.random() * 8)]
          })),
          mentors:
            Math.random() > 0.4
              ? Array.from({ length: Math.floor(Math.random() * 3) + 1 }, () => ({
                  name: `${surnames[Math.floor(Math.random() * surnames.length)]}${['先生', '夫子', '师父', '老师'][Math.floor(Math.random() * 4)]}`,
                  relation: ['启蒙老师', '师父', '学问导师', '人生导师'][Math.floor(Math.random() * 4)],
                  field: ['学问', '技艺', '武艺', '医术', '商道', '人生哲理'][Math.floor(Math.random() * 6)],
                  influence: '深远影响',
                  teachingPeriod: `${birthYear + 10 + Math.floor(Math.random() * 15)}-${birthYear + 15 + Math.floor(Math.random() * 20)}`
                }))
              : [],
          enemies:
            Math.random() > 0.8
              ? Array.from({ length: Math.floor(Math.random() * 2) + 1 }, () => ({
                  name: `${surnames[Math.floor(Math.random() * surnames.length)]}某`,
                  reason: ['商业竞争', '情感纠葛', '利益冲突', '误会积怨', '价值观分歧'][Math.floor(Math.random() * 5)],
                  severity: ['轻微', '一般', '严重'][Math.floor(Math.random() * 3)],
                  resolution: ['已和解', '互不往来', '仍有矛盾'][Math.floor(Math.random() * 3)]
                }))
              : [],
          socialCircles: Array.from({ length: Math.floor(Math.random() * 4) + 1 }, (_, i) => ({
            name: ['同乡会', '商会', '文人雅集', '慈善社', '读书会', '茶友会', '书画社', '诗社'][i],
            role: ['成员', '会员', '理事', '会长', '名誉会长'][Math.floor(Math.random() * 5)],
            joinDate: `${birthYear + 25 + Math.floor(Math.random() * 15)}-01-01`,
            contribution: ['积极参与', '热心公益', '组织活动', '资金支持'][Math.floor(Math.random() * 4)],
            reputation: ['声誉良好', '备受尊敬', '德高望重'][Math.floor(Math.random() * 3)]
          }))
        },

        // 其他信息
        location: currentAddress,
        notes: `档案完整，信息详实。${isAlive ? '当前健在，' : '已故，'}品德${karma > 50 ? '高尚' : karma > 0 ? '良好' : karma > -50 ? '一般' : '有待提升'}。`,
        lastUpdated: new Date().toISOString(),
        createdBy: '地府文书司',
        tags: ['正常档案', '信息完整'].concat(karma > 80 ? ['德行高尚'] : [], karma < -50 ? ['业力异常'] : [], Math.random() > 0.8 ? ['重点关注'] : [], age > 80 ? ['长寿'] : [], Math.random() > 0.9 ? ['传奇人物'] : []),
        dataQuality: {
          completeness: 85 + Math.floor(Math.random() * 15), // 85-100%
          accuracy: 90 + Math.floor(Math.random() * 10), // 90-100%
          lastVerified: new Date(Date.now() - Math.floor(Math.random() * 365) * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
        }
      }
    })
  }

  // 计算属性
  const filteredArchives = computed(() => {
    let result = archives.value

    // 搜索过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter(
        (archive) =>
          archive.name?.toLowerCase().includes(query) ||
          archive.id?.toString().includes(query) ||
          archive.basicInfo?.idCard?.toLowerCase().includes(query) ||
          archive.location?.toLowerCase().includes(query) ||
          archive.basicInfo?.currentAddress?.toLowerCase().includes(query)
      )
    }

    // 状态过滤
    if (filters.value.status !== 'all') {
      result = result.filter((archive) => archive.status === filters.value.status)
    }

    // 性别过滤
    if (filters.value.gender !== 'all') {
      result = result.filter((archive) => archive.gender === filters.value.gender)
    }

    // 年龄过滤
    result = result.filter((archive) => archive.age >= filters.value.ageRange[0] && archive.age <= filters.value.ageRange[1])

    return result
  })

  const totalCount = computed(() => archives.value.length)
  const aliveCount = computed(() => archives.value.filter((a) => a.status === 'alive').length)
  const deadCount = computed(() => archives.value.filter((a) => a.status === 'dead').length)
  const averageKarma = computed(() => {
    if (archives.value.length === 0) return 0
    const validArchives = archives.value.filter((archive) => archive.karma !== undefined && archive.karma !== null)
    if (validArchives.length === 0) return 0
    const sum = validArchives.reduce((acc, archive) => acc + (archive.karma || 0), 0)
    return Math.round(sum / validArchives.length)
  })

  // 方法
  const fetchArchives = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 200))

      // 生成假数据
      archives.value = generateMockData()
    } catch (error) {
      console.error('Failed to fetch archives:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取单个档案详情
  const getArchiveById = (id) => {
    return archives.value.find((archive) => archive.id === id)
  }

  // 添加档案
  const addArchive = async (archiveData) => {
    try {
      const newArchive = {
        id: Date.now(),
        name: archiveData.name || '',
        gender: archiveData.gender || 'male',
        age: 0,
        status: 'alive',
        karma: 0,
        lifespan: archiveData.lifespan || 75,
        avatar: `/avatars/${archiveData.gender === 'male' ? 'male' : 'female'}-1.png`,
        basicInfo: {
          fullName: archiveData.name || '',
          nickname: '',
          idCard: '',
          birthPlace: archiveData.birthPlace || '',
          currentAddress: archiveData.location || '',
          nationality: '汉族',
          bloodType: 'O',
          profession: archiveData.profession || '',
          education: '未知',
          maritalStatus: '未婚',
          height: 170,
          weight: 60,
          personalityTraits: ['善良', '诚实']
        },
        lifeHistory: {
          birthDate: archiveData.birthDate || new Date().toISOString().split('T')[0],
          deathDate: null,
          majorEvents: [],
          growthTrack: [],
          achievements: [],
          lifePhilosophy: '修身齐家治国平天下'
        },
        socialNetwork: {
          family: {
            parents: [],
            spouse: null,
            children: [],
            siblings: [],
            grandparents: []
          },
          friends: [],
          mentors: [],
          enemies: [],
          socialCircles: []
        },
        location: archiveData.location || '',
        notes: archiveData.notes || '新建档案，信息待完善',
        lastUpdated: new Date().toISOString(),
        createdBy: '地府文书司',
        tags: ['新建档案'],
        dataQuality: {
          completeness: 50,
          accuracy: 90,
          lastVerified: new Date().toISOString().split('T')[0]
        }
      }
      archives.value.unshift(newArchive)
      return { success: true, archive: newArchive }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 更新档案
  const updateArchive = async (id, archiveData) => {
    try {
      const index = archives.value.findIndex((a) => a.id === id)
      if (index !== -1) {
        archives.value[index] = {
          ...archives.value[index],
          ...archiveData,
          lastUpdated: new Date().toISOString()
        }
        return { success: true, archive: archives.value[index] }
      }
      return { success: false, error: '档案不存在' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 更新基础信息
  const updateBasicInfo = async (id, basicInfo) => {
    try {
      const archive = archives.value.find((a) => a.id === id)
      if (archive) {
        archive.basicInfo = { ...archive.basicInfo, ...basicInfo }
        archive.lastUpdated = new Date().toISOString()
        return { success: true }
      }
      return { success: false, error: '档案不存在' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 添加生命历程事件
  const addLifeEvent = async (id, event) => {
    try {
      const archive = archives.value.find((a) => a.id === id)
      if (archive) {
        const newEvent = {
          id: Date.now(),
          ...event,
          createdAt: new Date().toISOString()
        }
        archive.lifeHistory.majorEvents.push(newEvent)
        archive.lastUpdated = new Date().toISOString()
        return { success: true, event: newEvent }
      }
      return { success: false, error: '档案不存在' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 更新社会关系
  const updateSocialNetwork = async (id, networkData) => {
    try {
      const archive = archives.value.find((a) => a.id === id)
      if (archive) {
        archive.socialNetwork = { ...archive.socialNetwork, ...networkData }
        archive.lastUpdated = new Date().toISOString()
        return { success: true }
      }
      return { success: false, error: '档案不存在' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 删除档案
  const deleteArchive = async (id) => {
    try {
      const index = archives.value.findIndex((a) => a.id === id)
      if (index !== -1) {
        archives.value.splice(index, 1)
        return { success: true }
      }
      return { success: false, error: '档案不存在' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 设置搜索条件
  const setSearchQuery = (query) => {
    searchQuery.value = query
  }

  // 设置过滤条件
  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
  }

  // 重置过滤条件
  const resetFilters = () => {
    searchQuery.value = ''
    filters.value = {
      status: 'all',
      gender: 'all',
      ageRange: [0, 200]
    }
  }

  return {
    // 状态
    archives,
    loading,
    searchQuery,
    filters,

    // 计算属性
    filteredArchives,
    totalCount,
    aliveCount,
    deadCount,
    averageKarma,

    // 方法
    fetchArchives,
    getArchiveById,
    addArchive,
    updateArchive,
    updateBasicInfo,
    addLifeEvent,
    updateSocialNetwork,
    deleteArchive,
    setSearchQuery,
    setFilters,
    resetFilters
  }
})
